package com.yx.study.leet.questionList.questions;

import org.junit.Test;

import java.util.Arrays;

/**
 * 16. 最接近的三数之和
 * https://leetcode.cn/problems/3sum-closest/
 */
public class ThreeSumClosest16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int start = i + 1, end = nums.length - 1;
            while (start < end) {
                int sum = nums[start] + nums[end] + nums[i];
                if (Math.abs(target - sum) < Math.abs(target - ans))
                    ans = sum;
                if (sum > target) // 寻找更小的值
                    end--;
                else if (sum < target) // 寻找更大的值
                    start++;
                else
                    return ans;
            }
        }
        return ans;
    }

    @Test
    public void test(){
        int[] nums = new int[]{-1,2,1,-4};
        System.out.println(threeSumClosest(nums,2));
    }
}
